package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(new ObjectMapper().writeValueAsString(new JsonResult()));
        return false;
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String errorMsg = "登陆异常，请联系管理员";
        if (e != null){
            if(e instanceof UnknownAccountException){
                errorMsg = "用户名不存在";
            }else if(e instanceof IncorrectCredentialsException){
                errorMsg = "登陆密码错误";
            }
        }
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().print(new ObjectMapper().writeValueAsString(JsonResult.mark(errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //把异常信息打印出来，也能从页面中得知
        e.printStackTrace();
        return false;
    }

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //判断是否是登陆的请求
        if(isLoginRequest(request,response)){
            //判断是否已经有用户登陆过
            Subject subject = SecurityUtils.getSubject();
            //如果有就先注销掉
            if(subject.isAuthenticated()){
                subject.logout();
            }
        }
        //然后再调用父类中的方法允许登陆
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
